<template>
  <el-card>
    <h2>待审批报修单</h2>
    <el-table :data="orders" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="报修单ID" width="100"/>
      <el-table-column prop="orderNo" label="流程实例ID" width="180"/>
      <el-table-column prop="ownerId" label="业主ID" width="100"/>
      <el-table-column prop="houseId" label="房屋ID" width="100"/>
      <el-table-column prop="description" label="问题描述"/>
      <el-table-column prop="appointmentTime" label="预约时间" width="150"/>
      <el-table-column prop="priority" label="优先级" width="80">
        <template #default="{ row }">
          <el-tag :type="priorityType(row.priority)">
            {{ priorityText(row.priority) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag>{{ statusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openApprove(row)">审批</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 物业审批弹窗 (roleId=2) -->
    <el-dialog v-model="dialogVisible" title="物业审批报修单" width="400px" v-if="roleId === 2">
      <div>
        <el-form :model="approveForm">
          <el-form-item label="审批结果">
            <el-radio-group v-model="approveForm.approved">
              <el-radio :value="true">通过</el-radio>
              <el-radio :value="false">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="物业审批备注">
            <el-input v-model="approveForm.comment" type="textarea" placeholder="请输入审批意见"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">提交审批</el-button>
      </template>
    </el-dialog>

    <!-- 维修审批弹窗 (roleId=3) -->
    <el-dialog v-model="dialogVisible" title="维修审批报修单" width="400px" v-if="roleId === 3">
      <div>
        <el-form :model="approveForm">
          <el-form-item label="处理结果">
            <el-radio-group v-model="approveForm.completed">
              <el-radio :value="true">已完成</el-radio>
              <el-radio :value="false">未完成</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="维修备注">
            <el-input v-model="approveForm.comment" type="textarea" placeholder="请输入维修情况"/>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApprove">提交处理结果</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const orders = ref([])
const roleId = ref(null)
const loading = ref(false)
const dialogVisible = ref(false)

// 统一的表单数据结构，适配两种审批场景
const approveForm = ref({
  repairOrderId: null,
  approved: true,      // 物业审批用
  completed: true,     // 维修审批用
  comment: ''
})

function priorityText(val) {
  if (val === 1) return '紧急'
  if (val === 2) return '一般'
  if (val === 3) return '低'
  return '-'
}

function priorityType(val) {
  if (val === 1) return 'danger'
  if (val === 2) return 'warning'
  if (val === 3) return 'info'
  return ''
}

function statusText(val) {
  switch (val) {
    case 1: return '待审核'
    case 2: return '已受理'
    case 3: return '维修中'
    case 4: return '待验收'
    case 5: return '已完成'
    case 6: return '已取消'
    case 7: return '已驳回'
    default: return '-'
  }
}

function fetchOrders() {
  loading.value = true
  const token = sessionStorage.getItem('token')
  axios.get('/repair-server/property', {
    headers: {
      Authorization: token,
      token: token
    }
  })
      .then(res => {
        orders.value = res.data
      })
      .catch(() => {
        ElMessage.error('获取报修单失败')
      })
      .finally(() => {
        loading.value = false
      })
}

function openApprove(row) {
  // 根据角色初始化不同的表单默认值
  approveForm.value = {
    repairOrderId: row.id,
    approved: roleId.value === 2,  // 物业默认通过
    completed: roleId.value === 3, // 维修默认完成
    comment: ''
  }
  dialogVisible.value = true
}

function submitApprove() {
  const token = sessionStorage.getItem('token')
  const orderId = approveForm.value.repairOrderId

  // 根据角色调用不同的接口
  if (roleId.value === 2) {
    // 物业审批接口
    axios.post(`/repair-server/${orderId}/approve`, {
      approved: approveForm.value.approved,
      comment: approveForm.value.comment
    }, {
      headers: { Authorization: token ,token: token}
    })
        .then(res => {
          ElMessage.success(res.data.message || '物业审批成功')
          dialogVisible.value = false
          fetchOrders() // 刷新列表
        })
        .catch(err => {
          ElMessage.error(err.response?.data?.message || '物业审批失败')
        })
  } else if (roleId.value === 3) {
    // 维修审批接口
    axios.post(`/repair-server/${orderId}/handle`, {
      completed: approveForm.value.completed,
      repairResult: approveForm.value.comment
    }, {
      headers: { Authorization: token ,token: token}
    })
        .then(res => {
          ElMessage.success(res.data.message || '维修处理成功')
          dialogVisible.value = false
          fetchOrders() // 刷新列表
        })
        .catch(err => {
          ElMessage.error(err.response?.data?.message || '维修处理失败')
        })
  }
}

function fetchUserInfo() {
  loading.value = true
  const token = sessionStorage.getItem('token')
  axios.get('/uums-server/queryUser', {
    headers: {
        Authorization: token,
        token: token
    }
  })
      .then(res => {
        roleId.value = res.data.roleId
      })
      .catch(() => {
        ElMessage.error('获取用户信息失败')
      })
      .finally(() => {
        loading.value = false
      })
}

// 页面加载时初始化
onMounted(() => {
  fetchUserInfo()
  fetchOrders()
})
</script>